import os, sys, subprocess, unittest
import bs4
from os.path import expanduser

def export_dir(d, render, ignores):
    base_dir = d
    dirs = [d]
    while len(dirs) > 0:
        new_dirs = []
        for d in dirs:
            fnames = os.listdir(d)
            for fname in fnames:
                fpath = os.path.join(d, fname)
                relpath = os.path.relpath(fpath, base_dir)
                if os.path.isdir(fpath):
                    if not "%s/" % relpath in ignores:
                        new_dirs.append(fpath)
                else: # file
                    if relpath in ignores:
                        continue
                    fname, ext = os.path.splitext(fname)
                    if ext == '.org':
                        # convert org
                        if render.before_export(fpath):
                            if render.export(fpath):
                                if not render.after_export(fpath):
                                    print("After export failed: %s" % fpath)
                            else:
                                print("Export failed: %s" % fpath)
                        else:
                            print("Before export failed: %s" % fpath)
        dirs = new_dirs

if __name__ == "__main__":
    argv = sys.argv[1:]
    if len(argv) < 1:
        print("Usage python3 build.py <render_name>")
    elif sys.argv[1] == 'test':
        import common
        render = common.Render()
        export_dir(BASE_DIR, render)
    elif sys.argv[1] == 'hexo':
        print("Export as hexo...")
        from hexorender import HexoRender
        BASE_DIR=sys.argv[2]
        OUT_DIR=sys.argv[3]
        OUT_DIR=os.path.join(OUT_DIR, "source/_posts")
        render = HexoRender(BASE_DIR, OUT_DIR)
        export_dir(BASE_DIR, render, ['export/'])
    else:
        print("Unkown render")
